package com.yuntongxun.ecdemo.voicechat.ui.activity;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.CardView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.RequestParams;
import com.yuntongxun.ecdemo.R;
import com.yuntongxun.ecdemo.voicechat.api.ApiConstants;
import com.yuntongxun.ecdemo.voicechat.bean.PostResult;
import com.yuntongxun.ecdemo.voicechat.comman.Contants;
import com.yuntongxun.ecdemo.voicechat.comman.EventBusTags;
import com.yuntongxun.ecdemo.voicechat.presenter.ICommonRequestPresenter;
import com.yuntongxun.ecdemo.voicechat.presenter.impl.CommonRequestPresenterImpl;
import com.yuntongxun.ecdemo.voicechat.util.CustomToast;
import com.yuntongxun.ecdemo.voicechat.util.PreferenceUtils;
import com.yuntongxun.ecdemo.voicechat.util.http.HttpStatusUtil;
import com.yuntongxun.ecdemo.voicechat.util.iview.ICommonViewUi;

import java.io.IOException;
import java.io.InputStream;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.InjectView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

/**
 * 注册页面4-输入个人信息
 *
 * @author li_zhuonan
 * @version 1.0
 * @since 2016/11/15
 */
public class RegisterInfoActivity extends BaseChatActivity implements ICommonViewUi {


    @InjectView(R.id.country_img)
    ImageView flagImg;
    @InjectView(R.id.country_name_tv)
    TextView flagNameTv;
    @InjectView(R.id.gender_img)
    ImageView genderImg;
    @InjectView(R.id.age_tv)
    TextView ageTv;
    @InjectView(R.id.name_edt)
    EditText nameEdt;
    @InjectView(R.id.email_edt)
    EditText emailEdt;
    @InjectView(R.id.code_edt)
    EditText codeEdt;
    @InjectView(R.id.password_edt)
    EditText passwordEdt;
    @InjectView(R.id.password_confirm_edt)
    EditText passwordConfirmEdt;
    @InjectView(R.id.next_btn)
    Button nextBtn;
    @InjectView(R.id.get_vercode_btn)
    CardView getVercodeNext;
    @InjectView(R.id.vercode_tv)
    TextView loginVercodeTv;

    String gender="";


    @InjectView(R.id.terms_and_conditions)
    TextView termsAndConditionsTv;

    @OnClick(R.id.terms_and_conditions)
    public void onTermsClick(){
        startActivity(new Intent(this,TermsAndConditionsActivity.class));
    }

    public ICommonRequestPresenter iCommonRequestPresenter;

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_voice_chat_register4;
    }

    @Override
    protected void initViewsAndEvents() {
        setTitle("Register");
        initializeSecond();
        initData();
        iCommonRequestPresenter = new CommonRequestPresenterImpl(mContext, this);
    }

    private void initData(){
        termsAndConditionsTv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        String flagName = getIntent().getStringExtra(RegisterFlagActivity.FLAG);
        Log.e("flag", flagName + "");
        try {
            InputStream is = getAssets().open("flag/" + flagName + ".png");
            flagImg.setImageBitmap(BitmapFactory.decodeStream(is));
            flagNameTv.setText(flagName);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        gender=getIntent().getStringExtra(RegisterGenderActivity.GENDER);
        if (gender.endsWith(RegisterGenderActivity.MAN)){
            genderImg.setImageDrawable(getResources().getDrawable(R.drawable.man_check_true));
        }else{
            genderImg.setImageDrawable(getResources().getDrawable(R.drawable.woman_check_true));
        }

        ageTv.setText(getIntent().getStringExtra(RegisterAgeActivity.AGE));
    }

    @OnClick(R.id.get_vercode_btn)
    public void getVercodeClick(){
        getVercodeNext.setEnabled(false);
        toRequest(ApiConstants.EventTags.REGISTER_SMS);
    }

    @OnClick(R.id.next_btn)
    public void onNextClick(){
        if (TextUtils.isEmpty(nameEdt.getText().toString().trim())){
            showToastLong("Nickname cannot be empty!");
            return;
        }

        if (TextUtils.isEmpty(emailEdt.getText().toString().trim())){
            showToastLong("Please input valid email! ");
            return;
        }

        if (!isEmail(emailEdt.getText().toString().trim())){
            showToastLong("Please input valid email! ");
            return;
        }

        if (TextUtils.isEmpty(codeEdt.getText().toString().trim())){
            showToastLong("Verifycode cannot be empty!");
            return;
        }

        if (TextUtils.isEmpty(passwordEdt.getText().toString().trim())){
            showToastLong("Password cannot be empty!");
            return;
        }

        if (TextUtils.isEmpty(passwordConfirmEdt.getText().toString().trim())){
            showToastLong("Repassword cannot be empty!");
            return;
        }

        if (!passwordConfirmEdt.getText().toString().trim().endsWith(passwordEdt.getText().toString().trim())){
            showToastLong("Inconsistent passwords!");
            return;
        }


        toRequest(ApiConstants.EventTags.REGISTER);


    }

    private Timer timer;
    private int second = 60;
    private void initializeSecond() {
        int oldSecond = PreferenceUtils.getPrefInt(mContext,
                Contants.Preference.register_milliser_number, 60);

        long currentTime = System.currentTimeMillis();
        long oldTime = PreferenceUtils.getPrefLong(mContext,
                Contants.Preference.register_milliser, currentTime);
        long nowTime = currentTime;

        int distance = (int) ((nowTime - oldTime) / 1000);

        second = oldSecond - distance;

        if (second <= 0 || second == 60) {
            second = 60;
        } else {
            CountDown();
        }
    }

    private void CountDown() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            // TimerTask 是个抽象类,实现的是Runable类
            @Override
            public void run() {
                second--;
                myHandler.sendEmptyMessage(second);
                Log.e("second",second+"");
            }
        }, 0, 1000);
    }

    final Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (isFinishing()) {
                return;
            }

            if (msg.what > 0) {
                getVercodeNext.setEnabled(false);
                loginVercodeTv.setText("Wait(" + msg.what + "s)");
//                getVercodeNext.setCardBackgroundColor(getResources().getColor(R.color.gray2));
            } else {
                second = 60;
                loginVercodeTv.setText("Verify Code");
//                getVercodeNext.setCardBackgroundColor(getResources().getColor(R.color.colorPrimary));
                getVercodeNext.setEnabled(true);
                if (timer != null) {
                    timer.cancel();
                }
            }
        }
    };


    @Override
    public void toRequest(int eventTag) {
        if (eventTag == ApiConstants.EventTags.REGISTER_SMS) {
            //发送验证码
            String email = emailEdt.getText().toString();

            if (!isEmail(email)){
                showToastLong("Please input valid email! ");
                getVercodeNext.setEnabled(true);
                return;
            }

            RequestParams params = new RequestParams();
            params.put("email", email);
            iCommonRequestPresenter.request(eventTag, mContext, ApiConstants.Urls.REGISTER_SMS, params);

        }else if (eventTag == ApiConstants.EventTags.REGISTER){
            RequestParams params = new RequestParams();
            params.put("accountName", emailEdt.getText().toString().trim());
            params.put("accountPwd", passwordEdt.getText().toString().trim());
            params.put("gender", gender);
            params.put("age", ageTv.getText().toString().trim());
            params.put("country", flagNameTv.getText().toString().trim());
            params.put("code", codeEdt.getText().toString().trim());
            params.put("nickName", nameEdt.getText().toString().trim());
            params.put("nativeLanguage", "");
            params.put("learningLanguage", "");
            iCommonRequestPresenter.request(eventTag, mContext, ApiConstants.Urls.REGISTER, params);
        }
    }

    @Override
    public void getRequestData(int eventTag, String result) {
        if (eventTag == ApiConstants.EventTags.REGISTER_SMS) {
            //发送验证码
            CustomToast customToast = new CustomToast(this);

            customToast.setText(HttpStatusUtil.getStatusMsg(result));

            customToast.showToast(10000l);


            CountDown();
        }

        if (eventTag==ApiConstants.EventTags.REGISTER){

            showToastLong(HttpStatusUtil.getStatusMsg(result));

            PostResult postResult = new PostResult();
            postResult.setTag(EventBusTags.REGISTER_FINISH);
            EventBus.getDefault().post(postResult);
            Intent intent=new Intent(RegisterInfoActivity.this,VoiceChatLoginActivity.class);
            startActivity(intent);
            finish();

            PreferenceUtils.setPrefString(this, Contants.Preference.USER_NAME,emailEdt.getText().toString().trim());
            PreferenceUtils.setPrefString(this, Contants.Preference.USER_PSD,passwordEdt.getText().toString().trim());
        }
    }

    @Override
    public void onRequestSuccessException(int eventTag, String msg) {

        showToastLong(msg);
    }

    @Override
    public void onRequestFailureException(int eventTag, String msg) {
        showToastLong(msg);
    }

    @Override
    public void isRequesting(int eventTag, boolean status) {

        if (eventTag==ApiConstants.EventTags.REGISTER_SMS){
            return;
        }

        if (status) {
                showKProgress("Waiting");
            } else {
                dimissKProgress();
                getVercodeNext.setEnabled(true);
            }
    }

    public boolean isEmail(String email) {
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);
        return m.matches();
    }

    public void backToPage() {
        onBackPressed();

        if (second != 60) {
            PreferenceUtils.setSettingLong(mContext,
                    Contants.Preference.register_milliser, System.currentTimeMillis());
            PreferenceUtils.setPrefInt(mContext,
                    Contants.Preference.register_milliser_number, second);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            backToPage();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
